import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页',
      keepAlive: true
    }
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('../views/ArticleDetail.vue'),
    meta: {
      title: '文章详情',
      keepAlive: false
    }
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: () => import('../views/UserCenter.vue'),
    meta: {
      title: '个人中心',
      requireAuth: true,
      keepAlive: true
    }
  },
  {
    path: '/publish',
    name: 'ArticlePublish',
    component: () => import('../views/ArticlePublish.vue'),
    meta: {
      title: '发布文章',
      requireAuth: true,
      keepAlive: false
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 修改页面标题
  document.title = `${to.meta.title || '技术博客'}`
  
  // 判断该路由是否需要登录权限
  if (to.meta.requireAuth) {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      // 没有token，需要登录
      // 可以使用pinia的状态管理来控制登录弹窗的显示
      next('/')
    }
  } else {
    next()
  }
})

export default router 